package cn.jstars.datatocloud.modules.dict.task;

import java.util.List;
import java.util.Map;

import org.nutz.lang.Lang;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;

import cn.jstars.datatocloud.common.cache.Cache;
import cn.jstars.datatocloud.common.consts.Consts.DBConst;
import cn.jstars.datatocloud.common.consts.Consts.DataType;
import cn.jstars.datatocloud.common.utils.DataUtil;
import cn.jstars.datatocloud.common.utils.PageUtil;
import cn.jstars.datatocloud.modules.base.MqService;
import cn.jstars.datatocloud.modules.dict.entity.ClientLogErr;
import cn.jstars.datatocloud.modules.dict.service.DictService;

/**
 * 客户端错误日志级联任务类
 *
 * @author Elvish
 */
public class ClientLogErrTask implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(ClientLogErrTask.class);

    private MqService mqService;
    private DictService dictService;

    public ClientLogErrTask(MqService mqService, DictService dictService) {
        this.mqService = mqService;
        this.dictService = dictService;
    }

    @Override
    public void run() {

        try {
            // 查询未级联的数据
            List<ClientLogErr> logs = dictService.getClientlogerrs();
            // 没有就退出
            if (Lang.isEmpty(logs)) {
                return;
            }

            // 封装factoryId
            for (ClientLogErr clientLogErr : logs) {
                clientLogErr.setAlarmFactoryId(Cache.factoryId);
            }

            // 切分数据
            List<List<ClientLogErr>> pageList = PageUtil.paging(logs, 500);

            for (List<ClientLogErr> list : pageList) {
                // 组装数据
                Map<String, Object> dataMap = Maps.newHashMap();
                dataMap.put("type", "ClientLogErr");
                dataMap.put("data", JSON.toJSONString(list));

                // 封装发送数据
                String sendMsg = DataUtil.getMessage(DataType.DICT_DATA, DBConst.BASE_DATABASE,
                    DBConst.CLIENTLOGERR, Cache.factoryId, dataMap);

                try {
                    // 发送数据
                    mqService.convertAndSend(Cache.cloudMQQueueName, sendMsg);
                } catch (Exception e) {
                    LOGGER.error("发送clientlogerr数据异常，睡30秒", e);
                    Thread.sleep(30000);
                    continue;
                }

                // 更新数据库状态
                dictService.updateClientLogErrUploadStatus(list);
            }
        } catch (Exception e) {
            LOGGER.error("ClientLogErrTask发生异常", e);
        }


    }

}
